package com.gpj.learn.rocketmq.order;

import com.gpj.learn.rocketmq.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;

/**
 * @className OrderProducer
 * @description
 *   顺序消息的消息生产者
 * @author GPJ
 * @date 2021/4/24 15:43
 * @version 1.0
 **/
@Slf4j
public class OrderProducer {
	public static void main(String[] args) {
		DefaultMQProducer producer = new DefaultMQProducer("OrderProducerGroupName");
		producer.setNamesrvAddr(CommonConstants.ROCKETMQ_NAMESERVER_ADDR);
		try {
			producer.start();

			for (int groupIndex = 0; groupIndex < 10; groupIndex++) {
				for (int step = 1; step < 6; step++) {
					Message message = new Message(CommonConstants.DEFAULT_TOPIC_NAME,
							"tag-" + groupIndex, "key-" + step,
							("{grop:" + groupIndex + ",step:" + step + "}").getBytes(StandardCharsets.UTF_8));

					SendResult result = producer.send(message, (queues, msg, arg) -> {
						// 根据分组值,选择队列
						int index = ((int) arg) % queues.size();
						return queues.get(index);
					}, groupIndex);
					log.info("[{}]消息已发送:{}", result.getMsgId(), result);
				}
			}
		} catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
			log.error("消息发送失败:{}", e.getMessage(), e);
		}finally {
			producer.shutdown();
		}
	}
}
